package org.ihelpuoo.weboo.upload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.ihelpuoo.I;
import org.ihelpuoo.filepool.TempFilePool;
import org.ihelpuoo.io.DecodeUTF8EntityStream;
import org.ihelpuoo.io.StreamUtils;
import org.ihelpuoo.io.StringBufferOutputStream;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.parser.Inputer;
import org.ihelpuoo.parser.Parser;

public class FieldsLoader implements Parser
{
	private Map<String, Object>	values;
	private int[]				segs;
	private int[]				endl;
	private TempFilePool		factory;

	public FieldsLoader(String boundary, Map<String, Object> v, TempFilePool factory)
	{
		this.factory = factory;
		String sSeg = I.NEW_LINE + boundary + I.NEW_LINE;
		String sEndl = I.NEW_LINE + boundary + "--" + I.NEW_LINE + I.NEW_LINE;
		segs = new int[sSeg.length()];
		for (int i = 0; i < segs.length; i++)
			segs[i] = sSeg.charAt(i);
		endl = new int[sEndl.length()];
		for (int i = 0; i < endl.length; i++)
			endl[i] = sEndl.charAt(i);
		values = v;
	}

	public void parse(InputStream ins) throws LoaderException
	{
		try
		{
			int c;
			FieldHead head = null;
			while (-1 != (c = ins.read()))
			{
				head = new FieldHead();
				while (Inputer.DENY != head.input(c))
					c = ins.read();
				if (head.isBad())
					break;
				Object v;
				if (head.isForFile())
				{
					FileItem fi = new FileItem();
					fi.setOriginalPath(StreamUtils.decodeUTF8Entity(head.getValue("filename")));
					fi.setContentType(head.getValue("Content-Type"));
					File f = factory.getFile(fi.getExtension());
					fi.setFile(f);
					OutputStream ops = new BufferedOutputStream(new FileOutputStream(f));
					FieldValue.load(ins,ops,segs,endl);
					v = fi;
				}
				else
				{
					StringBuffer sb = new StringBuffer();
					FieldValue.load(ins,
							new DecodeUTF8EntityStream(new StringBufferOutputStream(sb)),segs,endl);
					v = sb.toString();
				}
				values.put(head.getName(),v);
			}
		}
		catch (IOException e)
		{
			throw new LoaderException(e);
		}
	}
}
